package com.icinfo.cloud.provider.peripheralinterface.datareport.service.impl;

import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.icinfo.cloud.provider.common.enums.YesOrNoEnum;
import com.icinfo.cloud.provider.peripheralinterface.datareport.service.IDataReportService;
import com.icinfo.cloud.provider.punish.common.datareport.dto.CollectReportDataDto;
import com.icinfo.cloud.provider.punish.common.datareport.mapper.DataReportSaveFailRecordMapper;
import com.icinfo.cloud.provider.punish.common.datareport.model.DataReportSaveFailRecord;
import com.icinfo.cloud.provider.punish.config.model.SysDepartParam;
import com.icinfo.cloud.provider.punish.config.service.ISysDepartParamService;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.HandleTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.PartiesReasonTypeEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseMainInfoMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseMainInfo;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.ICaseMainInfoService;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseMainInfoVo;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @Desc 描述
 * @Author mahan
 * @Date 2023/3/30
 */
@Service
@Slf4j
public class DataReportServiceImpl implements IDataReportService {

	@Value("${localDataReport.reportUrl}")
	private String reportUrl;
	@Value("${localDataReport.api.reportDataSave}")
	private String reportDataSaveApi;

	@Resource
	private CaseMainInfoMapper caseMainInfoMapper;
	@Resource
	private ISysDepartParamService sysDepartParamService;
	@Resource
	private DataReportSaveFailRecordMapper dataReportSaveFailRecordMapper;
	@Resource
	private ICaseMainInfoService caseMainInfoService;


	/**
	 * 案件信息数据上报数据处理
	 */
	@Override
	public int collectRsHisData() {

		Example example = new Example(CaseMainInfo.class);
		example.createCriteria().andEqualTo("caseTerritoryCode", "A017")
				.andCondition("case_regist_time is not null");
		List<CaseMainInfo> list = caseMainInfoMapper.selectByExample(example);
		int countNum = 0;
		for(CaseMainInfo caseMainInfo : list){
			//判断是否上报数据
			if (!checkIsAllowDataReport(caseMainInfo.getCaseOrgCode())) {
				continue;
			}
			CollectReportDataDto dto = new CollectReportDataDto();
			dto.setCaseId(caseMainInfo.getId());
			dto.setCaseTerritoryCode(caseMainInfo.getCaseTerritoryCode());
			//判断是否为多当事人，多当事人处罚告知阶段才会上报
			//多当事人
			if (PartiesReasonTypeEnum.MULTIPLE_PARTIES.getCode().equals(caseMainInfo.getCasePartiesReasonType())) {
				//处罚告知阶段以后才上报
				if (Arrays.asList("PUNISH_INFORM", "PUNISH_DECIDE", "PUNISH_EXECUTION", "CLOSE_ARCHIVING").contains(caseMainInfo.getCaseCurrentStageCode())) {
					if (HandleTypeEnum.PART_PUNISH.getCode().equals(caseMainInfo.getHandleType())) {
						dto.setCasePartyType("3");
					} else {
						dto.setCasePartyType("2");
					}
				}else {
					continue;
				}
			} else {//单当事人
				dto.setCasePartyType("1");
			}
			countNum ++;
			this.caseDataReport(dto);
		}
		return countNum;
	}

	/**
	 * 案件信息数据上报数据处理
	 *
	 * @param reportDataDto
	 */
	@Override
	public void caseDataReport(CollectReportDataDto reportDataDto) {
		CaseMainInfoVo caseMainInfo = caseMainInfoService.getCaseMainInfo(reportDataDto.getCaseId());
		//判断是否上报数据
		if (!checkIsAllowDataReport(caseMainInfo.getCaseOrgCode())) {
			return;
		}
		try {
			log.info("推送数据上报案件信息请求参数: {}", reportDataDto);
			String param = JSON.toJSONString(reportDataDto);
			String response = HttpUtil.createPost(reportUrl.concat(reportDataSaveApi)).body(param).execute().body();
			log.info("推送数据上报案件信息返回信息: {}", response);
		} catch (Exception e) {
			//记录错误数据
			DataReportSaveFailRecord dataReportSaveFailRecord = new DataReportSaveFailRecord();
			BeanUtils.copyProperties(reportDataDto, dataReportSaveFailRecord);
			dataReportSaveFailRecord.setId(UUID.fastUUID().toString(true));
			dataReportSaveFailRecord.setCreateTime(new Date());
			dataReportSaveFailRecord.setFailReason("PC服务---案件上报数据保存异常:" + e.toString());
			dataReportSaveFailRecordMapper.insert(dataReportSaveFailRecord);
			log.error("案件上报数据保存异常:{}", e);
			log.error("推送数据上报案件信息出现异常：", e);
		}
	}

	/**
	 * 判断是否开启上报
	 * 简易程序上报判断在app项目中写
	 *
	 * @param caseOrgCode
	 * @return
	 */
	private boolean checkIsAllowDataReport(String caseOrgCode) {
		if (StrUtil.isNotEmpty(caseOrgCode)) {
			SysDepartParam sysDepartParam = sysDepartParamService.getSysDepartParamByOrgCodeAndDeptCode(caseOrgCode, "");
			String isAllowDataReportStr = sysDepartParam.getIsAllowDataReport();
			if (YesOrNoEnum.YES.getCode().equals(isAllowDataReportStr)) {
				return true;
			}
		}
		return false;
	}
}
